<template>
  <div class="app-container">
    <!--老人数据-->
    <!--查询条件区-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入老人姓名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--快捷按钮区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
    </el-row>

    <!--表格数据区-->
    <el-table v-loading="loading" :data="agedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="老人ID" width="100" align="center" key="agedId" prop="agedId"/>
      <el-table-column label="姓名" width="100" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="性别" width="50" align="center" key="gender" prop="gender" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="生日" width="100" align="center" key="birthday" prop="birthday" :show-overflow-tooltip="true" />
      <el-table-column label="身份证号" width="150" align="center" key="idCard" prop="idCard" :show-overflow-tooltip="true" />
      <el-table-column label="地址" width="150" align="center" key="address" prop="address" :show-overflow-tooltip="true" />
      <el-table-column label="电话" width="150" align="center" key="phone" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column label="病史" width="150" align="center" key="illLog" prop="illLog" :show-overflow-tooltip="true" />
      <el-table-column label="用药史" width="150" align="center" key="medicineLog" prop="medicineLog" :show-overflow-tooltip="true" />
      <el-table-column label="备注" width="150" align="center" key="remark" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column
        label="操作"
        align="center"
        width="100"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

<!-- 添加或修改用户配置对话框 （包含2个对话框，其中添加联系人的为内层弹出框）-->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="选择生日">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" maxlength="18"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="病史">
              <el-input v-model="form.illLog" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用药史">
              <el-input v-model="form.medicineLog" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <div class="lianxiren-box">
        <div class="lianxiren-box-line">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd_lianxiren"
          >添加联系人</el-button>
        </div><br>
        <div class="lianxiren-box-line">
          <el-table v-loading="loading" :data="form.contactList">
            <el-table-column label="姓名" width="150" align="center" key="name" prop="name"/>
            <el-table-column label="电话" width="200" align="center" key="phone" prop="phone"/>
            <el-table-column label="类别" width="100" align="center" key="type" prop="type">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.contact_type" :value="scope.row.type"/>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="200"
              class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button v-if="scope.row.contactId!=undefined"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate_lianxiren(scope.row)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete_lianxiren(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!--下面是第二层弹出框-->
      <el-dialog width="30%" :title="innerTitle" :visible.sync="inner" append-to-body>
        <el-form ref="contactForm" :model="contactForm" :rules="rules2" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="contactForm.name" placeholder="请输入姓名" maxlength="30" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="contactForm.phone" placeholder="请输入手机号" maxlength="11"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
                <el-form-item label="类别" prop="type">
                  <el-select v-model="contactForm.type" placeholder="请选择类别">
                    <el-option
                      v-for="dict in dict.type.contact_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveContact">确 定</el-button>
          <el-button @click="cancelContact">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listAged,addAged,getAged,updateAged,delAged } from "@/api/business/aged";
//import { getToken } from "@/utils/auth";

export default {
  name: "Aged",
  dicts: ['sys_user_sex','contact_type'], //性别与联系人类型
  data() {
    return {
      //大表格相关
      loading: true, //表格遮罩层
      agedIds: [], //表格批量操作选中数组
      single: true, //表格批量操作非单个禁用
      multiple: true, //表格批量操作非多个禁用
      showSearch: true, //表格上方的大查询条件参数（是否显示搜索条件）
      queryParams: { //表格上方的大查询条件参数
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
        agedId: undefined
      },
      total: 0, //表格总条数
      agedList: [], //老人表格数据

      //弹出层相关
      title: "", //第一层弹出层标题
      innerTitle: "", //第二层弹出层标题
      open: false,//是否显示弹出层，第一层
      inner:false,//是否显示弹出层，第二层（子表联系人添加与修改）

      form: { //第一层老人基本信息表单参数
        agedId: undefined,
        name: undefined,
        gender: undefined,
        birthday: undefined,
        idCard: undefined,
        address: undefined,
        phone: undefined,
        illLog: undefined,
        medicineLog: undefined,
        remark: undefined,
        contactList: [],//子表对象数组
      },

      contactForm:{ //第二层弹框联系人表单参数
        contactId: undefined,
        agedId: undefined,
        name: undefined,
        phone: undefined,
        type: undefined,
      },

      //表单校验相关
      rules: { //第一层表单校验
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 1, max: 20, message: '姓名长度必须介于 1 和 20 之间', trigger: 'blur' },
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" },
        ],
        birthday: [
          { required: true, message: "生日不能为空", trigger: "blur" },
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          {
            pattern: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[X])$)$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "地址不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          },
        ]
      },
      rules2: { //第二层表单校验
      },
    };
  },
  watch: {
    //
  },
  created() {
    //初始化
    this.getList(); //获取全部老人列表
  },
  methods: {
    //查询老人列表
    getList() {
      this.loading = true;
      listAged(this.queryParams).then(response => {
        console.log("返回的老人列表数据==",response.rows);
        this.agedList = response.rows;
        //console.log("处理后的表格数据==",this.agedList);
        this.total = response.total;
        this.loading = false;
      });
    },
    //表格上方的大查询条件参数，点击搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum=1;
      this.getList();
    },
    //表格上方的大查询条件参数，点击重置按钮操作
    resetQuery() {
      this.resetForm("queryForm"); //调用全局函数
      this.handleQuery();
    },
    //表格多选框选中数据
    handleSelectionChange(selection) {
      this.agedIds = selection.map(item => item.agedId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    //表格上方，点击新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加老人";
    },
    //表格上方或是表格每行数据，点击修改按钮操作
    handleUpdate(row) {
      this.reset();
      const agedId = row.agedId || this.agedIds;
      getAged(agedId).then(response => {
        console.log("获取指定老人对象信息的返回值==",response.data)
        this.form = response.data;
        this.open = true;
        this.title = "修改老人";
      });
    },
    //表格上方或是表格每行数据，点击删除按钮操作
    handleDelete(row) {
      const agedId = row.agedId || this.agedIds;
      this.$modal.confirm('是否确认删除 "' + row.name + '" 这名老人吗？').then(function() {
        return delAged(agedId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    //第一层弹出框取消按钮
    cancel() {
      this.open = false;
      this.reset();//重置第一层表单
    },
    //第一层表单重置
    reset() {
      this.form = {
        agedId: undefined,
        name: undefined,
        gender: undefined,
        birthday: undefined,
        idCard: undefined,
        address: undefined,
        phone: undefined,
        illLog: undefined,
        medicineLog: undefined,
        remark: undefined,
        contactList:[],//子表对象数组
      };
      this.resetForm("form"); //调用全局函数
    },
    //第一层表单，点击提交按钮操作
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.type=1;
          this.form.status=0;
          console.log("提交的form==",this.form);
          if (this.form.agedId != undefined) {
            updateAged(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAged(this.form).then(response => {
              console.log("添加老人成功后返回值==",response);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    //以下是新补充的子表操作
    //新增按钮操作
    handleAdd_lianxiren() {
      //alert("添加子表");
      this.resetContactForm();//先初始化表单
      this.inner=true;
      this.innerTitle="添加联系人";
    },
    //内层保存按钮
    saveContact(){
      if(this.contactForm.contactId==undefined){ //这个属于全新添加
        var contactObj = JSON.parse(JSON.stringify(this.contactForm));//避免引用同一个对象，进行对象拷贝
        this.form.contactList.push(contactObj);
        this.resetContactForm();
      }else{ //这个是修改指定老人的联系人
        for(var i=0;i<this.form.contactList.length;i++){
          if(this.contactForm.contactId==this.form.contactList[i].contactId){
            this.form.contactList[i].name=this.contactForm.name;
            this.form.contactList[i].phone=this.contactForm.phone;
            this.form.contactList[i].type=this.contactForm.type;
            break;//结束循环
          }
        }
      }

      this.inner = false;//保存后是关闭还是清空后任然保留弹框，待定
    },
    //内层取消按钮
    cancelContact(){
      this.inner = false;
      this.resetContactForm();
    },
    //内层表单重置
    resetContactForm() {
      this.contactForm = {
        agedId: undefined,
        contactId: undefined,
        name: undefined,
        phone: undefined,
        type: undefined,
      };
      this.resetForm("contactForm"); //调用全局函数
    },
    //修改按钮操作
    handleUpdate_lianxiren(row) {
      console.log("修改子表当前行row对象==",row);
      this.resetContactForm();//先清空第二层表单
      this.innerTitle="修改联系人";
      this.inner=true;
      for(var i=0;i<this.form.contactList.length;i++){
        if(row.contactId==this.form.contactList[i].contactId){
          this.contactForm.contactId=row.contactId;
          this.contactForm.name=this.form.contactList[i].name;
          this.contactForm.phone=this.form.contactList[i].phone;
          this.contactForm.type=this.form.contactList[i].type;
          break;//结束循环
        }
      }
    },
    //删除按钮操作
    handleDelete_lianxiren(row) {
      console.log("删除子表当前行row对象==",row);
      for(var i=0;i<this.form.contactList.length;i++){
        if(row.name==this.form.contactList[i].name && row.phone==this.form.contactList[i].phone){
          this.form.contactList.splice(i,1);
          break;//结束循环
        }
      }
      // if(row.contactId==undefined){
      //   //大表单未提交状态下
      // }else{
      //   //已提交有子表行id的情况
      // }
    },
  }
};
</script>
<style scoped lang="scss">
.lianxiren-box{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.lianxiren-box-line{
  width: 90%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
